package com.starkuz.controllers;

import com.starkuz.dao.ifaces.leads.CtrDao;
import com.starkuz.dao.ifaces.leads.LaunDao;
import com.starkuz.dao.ifaces.leads.LeadDao;
import com.starkuz.dao.ifaces.OrderDao;
import com.starkuz.dao.ifaces.sites.CtrSiteDao;
import com.starkuz.dao.ifaces.sites.LaunSiteDao;
import com.starkuz.dao.ifaces.visits.VisitCtrDao;
import com.starkuz.dao.ifaces.visits.VisitLaunDao;
import com.starkuz.dao.ifaces.visits.VisitLeadDao;
import com.starkuz.dao.ifaces.sites.LeadSiteDao;
import com.starkuz.dao.ifaces.sites.OrderSiteDao;
import com.starkuz.dto.FormFieldsDto;
import com.starkuz.dto.SetPeriodDto;
import com.starkuz.model.Order;
import com.starkuz.model.User;
import com.starkuz.model.sites.CtrSite;
import com.starkuz.model.sites.LaunSite;
import com.starkuz.model.sites.LeadSite;
import com.starkuz.model.sites.OrderSite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@Controller
public class OfficeController {

    @Autowired
    private LeadSiteDao leadSiteDao;

    @Autowired
    private VisitLeadDao visitLeadDao;

    @Autowired
    private LeadDao leadDao;

    @Autowired
    private OrderSiteDao orderSiteDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private CtrSiteDao ctrSiteDao;

    @Autowired
    private CtrDao ctrDao;

    @Autowired
    private VisitCtrDao visitCtrDao;

   @Autowired
   private LaunSiteDao launSiteDao;

   @Autowired
   private VisitLaunDao visitLaunDao;


   @Autowired
   private LaunDao launDao;

    public void setLaunDao(LaunDao launDao) {
        this.launDao = launDao;
    }

    public void setVisitLaunDao(VisitLaunDao visitLaunDao) {
        this.visitLaunDao = visitLaunDao;
    }

    public void setLaunSiteDao(LaunSiteDao launSiteDao) {
        this.launSiteDao = launSiteDao;
    }

    public void setCtrSiteDao(CtrSiteDao ctrSiteDao) {
        this.ctrSiteDao = ctrSiteDao;
    }

    public void setVisitLeadDao(VisitLeadDao visitLeadDao) {
        this.visitLeadDao = visitLeadDao;
    }

    public void setVisitCtrDao(VisitCtrDao visitCtrDao) {
        this.visitCtrDao = visitCtrDao;
    }

    public void setLeadSiteDao(LeadSiteDao leadSiteDao) {
        this.leadSiteDao = leadSiteDao;
    }

    public void setLeadDao(LeadDao leadDao) {
        this.leadDao = leadDao;
    }

    public void setOrderSiteDao(OrderSiteDao orderSiteDao) {
        this.orderSiteDao = orderSiteDao;
    }

    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public void setCtrDao(CtrDao ctrDao) {
        this.ctrDao = ctrDao;
    }

    @RequestMapping(value = "/userhome_info.html", method = RequestMethod.GET)
    public String userhome_info(FormFieldsDto formField, HttpServletRequest req, Map model) throws IOException {
        if (!isActiveUser(req)){
            return "redirect:index.html";
        }
        model.put("formField", formField);
        return "userhome_info";
    }

    @RequestMapping(value = "/userhome_orders.html", method = RequestMethod.GET)
    public String userhome_orders(FormFieldsDto formField, HttpServletRequest req, Map model) throws IOException {
        if (!isActiveUser(req)){
            return "redirect:index.html";
        }
        User user = (User) req.getSession().getAttribute("user");
        List<OrderSite> order_sites = orderSiteDao.getAllOrderSitesForUser(user.getId());
        List<Order> orders = orderDao.getAllOrdersByUserId(user.getId());
        model.put("ordersites", order_sites);
        model.put("orders", orders);
        model.put("formField", formField); //для вывода новостей и версии
        return "userhome_orders";
    }

    //    private List<OrderSite> addOrdersToList(List<OrderSite> sites) {
//        for (OrderSite site : sites) {
////            site.setVisits(orderDao.countAllVisitsOfPage(site.getId()));
//        }
//        return sites;

    @RequestMapping(value = "/userhome_lead.html", method = RequestMethod.GET)
    public String userhome_stat(FormFieldsDto formField, HttpServletRequest req, SetPeriodDto dto, Map model) throws IOException {
        if (!isActiveUser(req)){
            return "redirect:index.html";
        }
        model.put("setPeriod", dto);
        User user = (User) req.getSession().getAttribute("user");

        List<LeadSite> lead_sites = leadSiteDao.getAllActualLeadSitesForUser(user.getId());
        lead_sites = addLeadVisitsToList(lead_sites);
        lead_sites = addLeadsToList(lead_sites);
        calculateConversionsAndDeclinesToLeads(lead_sites);
        model.put("leadsites", lead_sites);
        model.put("formField", formField);
        return "userhome_leads";
    }

    private List<LeadSite> calculateConversionsAndDeclinesToLeads(List<LeadSite> sites) {
        for (LeadSite site : sites) {
            if (site.getLeads() == null || site.getLeads() == 0 || site.getVisits() == null || site.getVisits() == 0) {
                site.setDeclines(0F);         //если делимое или делитель ноль, то отказы и коверсия равны нулю
                site.setConversion(0F);
            } else {
                Float leads = Float.valueOf(site.getLeads());
                Float visits = Float.valueOf(site.getVisits());
                Float conversion = (leads / visits * 100F);
                site.setConversion(conversion);
                Float declines = 100F - conversion;
                site.setDeclines(declines);
            }
        }
        return sites;
    }

    private List<LeadSite> addLeadVisitsToList(List<LeadSite> sites) {
        for (LeadSite site : sites) {
            site.setVisits(visitLeadDao.countAllVisitsOfPage(site.getId()));
        }
        return sites;
    }

    private List<LeadSite> addLeadsToList(List<LeadSite> sites) {
        for (LeadSite site : sites) {
            site.setLeads(leadDao.countLeadBySiteId(site.getId()));
        }
        return sites;
    }

    @RequestMapping(value = "/userhome_ctr.html", method = RequestMethod.GET)
    public String userhome_ctr(FormFieldsDto formField, HttpServletRequest req, SetPeriodDto dto, Map model) throws IOException {
        if (!isActiveUser(req)){
            return "redirect:index.html";
        }
        model.put("setPeriod", dto);
        User user = (User) req.getSession().getAttribute("user");

        List<CtrSite> ctr_sites = ctrSiteDao.getAllActualCtrSitesForUser(user.getId());
        ctr_sites = addCtrlVisitsToList(ctr_sites);
        ctr_sites = addCtrlsToList(ctr_sites);
        calculateConversionsAndDeclinesToCtrs(ctr_sites);
        model.put("ctrsites", ctr_sites);
        model.put("formField", formField);
        return "userhome_ctrs";
    }  
    
    @RequestMapping(value = "/userhome_laun.html", method = RequestMethod.GET)
    public String userhome_laun(FormFieldsDto formField, HttpServletRequest req, SetPeriodDto dto, Map model) throws IOException {
        if (!isActiveUser(req)){
            return "redirect:index.html";
        }
        model.put("setPeriod", dto);
        User user = (User) req.getSession().getAttribute("user");

        List<LaunSite> laun_sites = launSiteDao.getAllActualLaunSitesForUser(user.getId());
        laun_sites = addLaunVisitsToList(laun_sites);
        laun_sites = addLaunsToList(laun_sites);
     // calculateConversionsAndDeclinesToCtrs(laun_sites, user.);      //todo: сделать
        model.put("launsites", laun_sites);
        model.put("formField", formField);
        return "userhome_launs";
    }

    private List<LaunSite> addLaunsToList(List<LaunSite> sites) {
        for (LaunSite site : sites) {
            site.setLauns(launDao.countLaunBySiteId(site.getId()));
        }
        return sites;
    }
    //Блок методов работы с Laun страничками начало
    private List<LaunSite> addLaunVisitsToList(List<LaunSite> sites) {
        for (LaunSite site : sites) {
            site.setVisits(visitLaunDao.countAllVisitsOfPage(site.getId()));
        }
        return sites;
    }


    private List<CtrSite> addCtrlsToList(List<CtrSite> sites) {
        for (CtrSite site : sites) {
            site.setCtrs(ctrDao.countCtrBySiteId(site.getId()));
        }
        return sites;
    }

    //Блок методов работы с CRT страничками начало
    private List<CtrSite> addCtrlVisitsToList(List<CtrSite> sites) {
        for (CtrSite site : sites) {
            site.setVisits(visitCtrDao.countAllVisitsOfPage(site.getId()));
        }
        return sites;
    }

    //Блок методов работы с CRT страничками конец

//    }
    private List<CtrSite> calculateConversionsAndDeclinesToCtrs(List<CtrSite> sites) {
        for (CtrSite site : sites) {
            if (site.getCtrs() == null || site.getCtrs() == 0 || site.getVisits() == null || site.getVisits() == 0) {
                site.setDeclines(0F);         //если делимое или делитель ноль, то отказы и коверсия равны нулю
                site.setConversion(0F);
            } else {
                Float ctrs = Float.valueOf(site.getCtrs());
                Float visits = Float.valueOf(site.getVisits());
                Float conversion = (ctrs / visits * 100F);
                site.setConversion(conversion);
                Float declines = 100F - conversion;
                site.setDeclines(declines);
            }
        }
        return sites;
    }


    private boolean isActiveUser(HttpServletRequest request){
        boolean answer = false;
        HttpSession session =  request.getSession();
        if (session.getAttribute("user") != null) {
            User user = (User)session.getAttribute("user");
            if (!user.getStatus().equals(User.INACTIVE)){
                answer = true;
            }
        }
        return answer;
    }
}
